package com.atguigu.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

//ConstraintValidator<检验注解,标注在那个类型的参数上>
public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {

    private Set<Integer> set = new HashSet<>();

    //初始化方法
    @Override
    public void initialize(ListValue constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        int[] vals = constraintAnnotation.vals();
        for (int val : vals) {
            //实际操作时需要判空
            set.add(val);
        }
    }

    //判断是否校验成功
    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
        //@ListValue(vals={0,1}) 如果上送的参数不在集合中，则校验不通过
        //如果集合中包含了值返回true，不包含返回false
        return set.contains(integer);
    }
}
